<?php
/*
 +----------------------------------------------------------------------
 + Title        : RequestParam 控制器
 + Author       : Randy_chen
 + Version      : V1.0.0.1
 + Initial-Time : 2020/5/6 11:14
 + Last-time    : 2020/5/6 11:14+ 86187
 + Desc         : RequestParam
 +----------------------------------------------------------------------
*/


namespace myAnnotation\rules;


class RequestParamRule {
    /**
     *
     * @param \myAnnotation\Annotation\RequestParam $requestParam
     *
     * @throws \Exception
     * @author : Randy_chen
     * @Date   : 2020/5/6
     * @Time   : 11:43
     */
    function run(\myAnnotation\Annotation\RequestParam $requestParam){
        $requestParams = app('request')->only($requestParam->fields, $requestParam->method ?: 'param');
        if ($formatRules = $requestParam->json) {
            $this->formatRequestParams($formatRules, $requestParams);
        }
        if ($requestParam->mapping) {
            $mapping = [];
            foreach ($requestParams as $key => $value) {
                if (isset($requestParam->mapping[$key])) {
                    $mapping[$requestParam->mapping[$key]] = $value;
                } else {
                    $mapping[$key] = $value;
                }
            }
            $requestParams = $mapping;
        }
        app('request')->requestParam = $requestParams;
    }

    /**
     * 格式化请求参数
     *
     * @param array $rules
     * @param       $requestParams
     *
     * @throws \Exception
     */
    protected function formatRequestParams(array $rules, &$requestParams) {
        foreach ($rules as $field => $rule) {
            if (is_int($field)) {
                $field = (string) $rule;
            }
            if (isset($requestParams[$field])) {
                $data = json_decode($requestParams[$field], true);
                if (is_null($data)) {
                    throw new \Exception($field . '字段的值无法json反序列化');
                }
                // 过滤json数据的字段
                if (is_array($rule) && $rule) {
                    foreach ($data as $k => $v) {
                        if (is_string($k)) {//一维数组
                            if (!in_array($k, $rule)) {
                                unset($data[$k]);
                            }
                        } else if (is_int($k) && is_array($v)) {//二维数组
                            foreach ($v as $kk => $vv) {
                                if (!in_array($kk, $rule)) {
                                    unset($data[$k][$kk]);
                                }
                            }
                        }
                    }
                }
                $requestParams[$field] = $data;
            }
        }
    }
}